package com.alax.interfaces.controller;

import com.alax.common.core.controller.BaseController;
import com.alax.common.core.domain.AjaxResult;
import com.alax.interfaces.domain.dto.DashboardSummaryDTO;
import com.alax.interfaces.domain.dto.NameValueDTO;
import com.alax.interfaces.domain.dto.TimeSeriesDTO;
import com.alax.interfaces.domain.dto.RealtimeStatsDTO;
import com.alax.interfaces.service.IDashboardService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/dashboard") // 使用 /dashboard 作为基础路径
public class DashboardController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(DashboardController.class);

    @Autowired
    private IDashboardService dashboardService;

    /**
     * 获取仪表盘总览数据
     */
    @GetMapping("/summary")
    @PreAuthorize("@ss.hasPermi('monitor:dashboard:view')") // 假设一个权限标识
    public AjaxResult getSummary() {
        try {
            DashboardSummaryDTO summary = dashboardService.getDashboardSummary();
            return AjaxResult.success(summary);
        } catch (Exception e) {
            log.error("获取仪表盘总览数据失败", e);
            return AjaxResult.error("获取总览数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取调用趋势数据
     * @param days 查询天数 (默认为 7)
     */
    @GetMapping("/callsTrend")
    @PreAuthorize("@ss.hasPermi('monitor:dashboard:view')")
    public AjaxResult getCallsTrend(@RequestParam(value = "days", defaultValue = "7") int days) {
        if (days <= 0 || days > 365) {
            return AjaxResult.error("查询天数必须在 1 到 365 之间");
        }
        try {
            TimeSeriesDTO trend = dashboardService.getCallsTrend(days);
            return AjaxResult.success(trend);
        } catch (Exception e) {
            log.error("获取调用趋势数据失败, days={}", days, e);
            return AjaxResult.error("获取调用趋势失败：" + e.getMessage());
        }
    }

    /**
     * 获取调用状态分布数据
     * @param period 时间段 (默认为 "today")
     */
    @GetMapping("/statusDistribution")
    @PreAuthorize("@ss.hasPermi('monitor:dashboard:view')")
    public AjaxResult getStatusDistribution(@RequestParam(value = "period", defaultValue = "today") String period) {
        try {
            List<NameValueDTO> distribution = dashboardService.getStatusDistribution(period);
            return AjaxResult.success(distribution);
        } catch (Exception e) {
            log.error("获取调用状态分布数据失败, period={}", period, e);
            return AjaxResult.error("获取状态分布失败：" + e.getMessage());
        }
    }

    /**
     * 获取Top API排行数据
     * @param limit 返回数量 (默认为 8)
     * @param period 时间段 (默认为 "today")
     */
    @GetMapping("/topApis")
    @PreAuthorize("@ss.hasPermi('monitor:dashboard:view')")
    public AjaxResult getTopApis(@RequestParam(value = "limit", defaultValue = "8") int limit,
                                 @RequestParam(value = "period", defaultValue = "today") String period) {
        if (limit <= 0 || limit > 50) {
            return AjaxResult.error("返回数量必须在 1 到 50 之间");
        }
        try {
            List<NameValueDTO> topApis = dashboardService.getTopApis(limit, period);
            return AjaxResult.success(topApis);
        } catch (Exception e) {
            log.error("获取Top API排行数据失败, limit={}, period={}", limit, period, e);
            return AjaxResult.error("获取Top API失败：" + e.getMessage());
        }
    }

    /**
     * 获取实时统计数据
     */
    @GetMapping("/realtime")
    @PreAuthorize("@ss.hasPermi('monitor:dashboard:view')")
    public AjaxResult getRealtimeStats() {
        try {
            RealtimeStatsDTO stats = dashboardService.getRealtimeStats();
            return AjaxResult.success(stats);
        } catch (Exception e) {
            log.error("获取实时统计数据失败", e);
            return AjaxResult.error("获取实时统计数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户行为统计
     */
    @GetMapping("/userBehavior")
    @PreAuthorize("@ss.hasPermi('monitor:dashboard:view')")
    public AjaxResult getUserBehaviorStats(
            @RequestParam(value = "userId", required = false) Long userId,
            @RequestParam(value = "period", defaultValue = "today") String period) {
        try {
            List<Map<String, Object>> stats = dashboardService.getUserBehaviorStats(userId, period);
            return AjaxResult.success(stats);
        } catch (Exception e) {
            log.error("获取用户行为统计失败, userId={}, period={}", userId, period, e);
            return AjaxResult.error("获取用户行为统计失败：" + e.getMessage());
        }
    }
}